<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="链接邀请记录" width="1200px" destroyOnClose>
    <BasicTable @register="registerTable" >
      <template #status="{ record }">
        <Tag :color="record.isValid ? 'success' : 'red'">
          {{ record.isValid ? '有效' : '无效' }}
        </Tag>
        <span v-if="record.isValid">
          有效期：{{ record.endDate }}
        </span>
      </template>
    </BasicTable>
  </BasicModal>
  <InviteUserDetail @register="registerFormDetail"/>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
import { inviteColumns } from '../user.data';
import { pageUserInvite, disableInvite } from '../user.api';
import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
import { useMessage } from '/@/hooks/web/useMessage'
import { Tag } from 'ant-design-vue'
import InviteUserDetail from './InviteUserDetail.vue';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'

const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const { clipboardRef, copiedRef } = useCopyToClipboard();
const { createMessage } = useMessage();
const [registerFormDetail, { openModal: openFormDetail }] = useModal()

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ confirmLoading: false, showCancelBtn: false, showOkBtn: false });
  isUpdate.value = !!data?.isUpdate;

});

const actionColumn: BasicColumn = {
  width: 180,
  title: '操作',
  dataIndex: 'action',
  fixed: 'right',
  slot: 'tableActions',
  actions:  (record: Recordable) => [
    {
      label: '禁用',
      color: 'error',
      ifShow: record.isValid,
      popConfirm: {
        title: '禁用后，用户无法通过该链接加入企业',
        confirm: handleDisable.bind(null, record),
      },
    },
    {
      label: '复制链接',
      ifShow: record.isValid,
      onClick: handleCopyLink.bind(null, record),
    },
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    }
  ],
  dropDownActions: (record: Recordable) => [
    
  ]
}

const [registerTable, { reload, expandAll, collapseAll, expandCollapse }] = useTable({
  api: pageUserInvite,
  columns: inviteColumns,
  bordered: false,
  beforeFetch: (params) => {
    return params;
  },
  showTableSetting: false,
  useSearchForm: false,
  isTreeTable: false,
  pagination: true,
  canResize: true,
  showIndexColumn: false,
  rowKey: 'id',
  actionColumn,
})

const handleCopyLink = (record) => {
  clipboardRef.value = record.inviteLink;
  if (unref(copiedRef)) {
    createMessage.success('复制成功');
  }
}

const handleDisable = async (record) => {
  await disableInvite({ id: record.id })
  reload()
}

const handleDetail = (record) => openFormDetail(true, { record })
</script>
